package mq

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/gorilla/websocket"
	"sync"
)

// WebSocket连接管理器
type WebSocketManager struct {
	conn     *websocket.Conn
	url      string
	isClosed bool
	mu       sync.Mutex
}

// NewWebSocketManager 创建新的WebSocket管理器
func InitWebSocketManager(url string) (*WebSocketManager, error) {
	// 初始化连接
	conn, _, err := websocket.DefaultDialer.Dial(url, nil)
	if err != nil {
		return nil, fmt.Errorf("连接WebSocket失败: %v", err)
	}

	return &WebSocketManager{
		conn:     conn,
		url:      url,
		isClosed: false,
		mu:       sync.Mutex{},
	}, nil
}

// Close 安全关闭WebSocket连接
func (m *WebSocketManager) Close() error {
	m.mu.Lock()
	defer m.mu.Unlock()

	if m.isClosed {
		return nil
	}

	if m.conn != nil {
		err := m.conn.Close()
		m.conn = nil // 确保标记为nil
		m.isClosed = true
		return err
	}

	m.isClosed = true
	return nil
}

// LogMessage 定义消息结构体
type LogMessage struct {
	Type    string `json:"type"`
	Content string `json:"content"`
}

// 发送消息
func (m *WebSocketManager) SendMessage(logLine, msgType string) error {
	// 防御性检查：确保实例不为nil
	/*	if m == nil {
		return errors.New("WebSocketManager实例为nil")
	}*/
	m.mu.Lock()
	defer m.mu.Unlock()

	if m.isClosed {
		return errors.New("WebSocket已关闭")
	}

	msg := LogMessage{Type: msgType, Content: logLine}
	jsonData, err := json.Marshal(msg)
	if err != nil {
		return fmt.Errorf("序列化失败: %v", err)
	}

	return m.conn.WriteMessage(websocket.TextMessage, jsonData)
}

//
//// 使用示例
//func main() {
//	url := "ws://example.com/logger"
//	manager, err := NewWebSocketManager(url)
//	if err != nil {
//		// 处理错误
//	}
//	defer manager.Close()
//
//	// 发送消息
//	manager.SendMessage("任务开始", "log")
//	// ... 其他操作
//	// 主动关闭连接
//	manager.Close()
//}
//func init() {
//	url := fmt.Sprintf("ws://%s:%d/ssh/agentLogger?executingId=%s", setting.Setting.ServerIP, 8280, req.ExecuteID)
//	//url := fmt.Sprintf("ws://%s:%d/ssh/logger?nodeUUID=%s&executeLoggerUUID=%s", setting.Setting.ServerIP, 8280, req.NodeUuid, req.ExecuteID)
//	manager, err := NewWebSocketManager(url)
//	//logs.Infof("url is : %v\n", url)
//}
